#include "QSketchRectangleAction.h"
#include "Sketch/QSketchManager.h"
#include "Sketch/QSketch.h"
#include <BRepBuilderAPI_MakePolygon.hxx>
#include "Core/MainWindow.h"
#include "Core/TempActorManager.h"
#include <vtkProperty.h>

QSketchRectangleAction::QSketchRectangleAction(QSketchManager* parent, MainWindow* mainWindow)
	: QSketchCurveAction(parent, mainWindow)
{
}

QSketchRectangleAction::~QSketchRectangleAction()
{
}

void QSketchRectangleAction::StartCreate()
{
	std::cout << "QSketchRectangleAction::StartCreate" << std::endl;
}

void QSketchRectangleAction::OnMouseMove(const gp_Pnt& point)
{
}

void QSketchRectangleAction::OnLeftDown(const gp_Pnt& point)
{
	if (!bIsFirstConfirm)
	{
		m_firstPoint = point;
		bIsFirstConfirm = true;

		m_firstPointActorID = m_mainWindow->GetTempActorManager()->GetUnallocatedActor(0.01);
		m_mainWindow->GetTempActorManager()->SetActorVisible(m_firstPointActorID, true, point);
	}
	else
	{
        m_secondPoint = point;

		gp_Trsf GToL = m_sketchManager->GetCurrentSketch()->GetGlobalToLocalTransform();
		gp_Trsf LToG = m_sketchManager->GetCurrentSketch()->GetLocalToGlobalTransform();

		// 1. 全局坐标系转局部坐标系
		gp_Pnt localPoint1 = m_firstPoint.Transformed(GToL);
		gp_Pnt localPoint2 = m_secondPoint.Transformed(GToL);
		// 2. 计算局部坐标顶点
		double x1 = localPoint1.X(), y1 = localPoint1.Y();
		double x2 = localPoint2.X(), y2 = localPoint2.Y();
		gp_Pnt localP1(x1, y1, 0);
		gp_Pnt localP2(x2, y1, 0);
		gp_Pnt localP3(x2, y2, 0);
		gp_Pnt localP4(x1, y2, 0);
		// 3. 局部坐标系转全局坐标系
		gp_Pnt globalP1 = localP1.Transformed(LToG);
		gp_Pnt globalP2 = localP2.Transformed(LToG);
		gp_Pnt globalP3 = localP3.Transformed(LToG);
		gp_Pnt globalP4 = localP4.Transformed(LToG);

		// 4. 生成线框
		Handle(QIVtkSelectionPipeline) actor = m_mainWindow->createRectangle(globalP1, globalP2, globalP3, globalP4);
		actor->m_featureShape.reset(new FeatureShapeRectangle(actor->OccShape(), globalP1, globalP2, globalP3, globalP4));
		m_sketchManager->m_points[EVertexType::EdgeEndVertex].push_back(globalP1);
		m_sketchManager->m_points[EVertexType::EdgeEndVertex].push_back(globalP2);
		m_sketchManager->m_points[EVertexType::EdgeEndVertex].push_back(globalP3);
		m_sketchManager->m_points[EVertexType::EdgeEndVertex].push_back(globalP4);
		m_sketchManager->m_points[EVertexType::EdgeDividedVertex].push_back((globalP1 + globalP2) * 0.5);
		m_sketchManager->m_points[EVertexType::EdgeDividedVertex].push_back((globalP2 + globalP3) * 0.5);
		m_sketchManager->m_points[EVertexType::EdgeDividedVertex].push_back((globalP3 + globalP4) * 0.5);
		m_sketchManager->m_points[EVertexType::EdgeDividedVertex].push_back((globalP4 + globalP1) * 0.5);
		m_sketchManager->EndCreateSketchCurve(actor);
	}
}

void QSketchRectangleAction::Reset()
{
	m_mainWindow->GetTempActorManager()->FreeActor(m_firstPointActorID);

	m_firstPoint = gp_Pnt();
    m_secondPoint = gp_Pnt();
	bIsFirstConfirm = false;
	m_firstPointActorID = 255;
}
